//
//  CCDHttpBaseTool.m
//  crowd
//
//  Created by 马腾飞 on 16/4/14.
//  Copyright © 2016年 caocaod.com. All rights reserved.
//

#import "CCDHttpBaseTool.h"
#define REQUESTURL @""


static NSString *const kBaseURLString = REQUESTURL;
@implementation AFHttpClient

+ (instancetype)sharedClient{
    
    static AFHttpClient *sharedClient = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
//        AFJSONRequestSerializer
        sharedClient = [[AFHttpClient alloc]initWithBaseURL:[NSURL URLWithString:kBaseURLString]];
        sharedClient.responseSerializer = [AFJSONResponseSerializer serializer];
        sharedClient.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/javascript",@"text/plain", nil];
        
    });
    return sharedClient;
}

@end


@implementation CCDHttpBaseTool

#pragma mark - AFN网络请求
#pragma mark POST请求
+ (void)postWithPath:(NSString *)path
              params:(NSDictionary *)params
             progress:(UIProgressView *)progressView
             success:(HttpSuccessBlock)success
             failure:(HttpFailureBlock)failure {
    AFHttpClient *manager = [AFHttpClient sharedClient];
    manager.requestSerializer.timeoutInterval = 5;
    [manager POST:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        [progressView setProgress:uploadProgress.fractionCompleted];
    }  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success == nil) return;
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure == nil) return;
        failure(error);
    }];
}

#pragma mark GET请求
+ (void)getWithPath:(NSString *)path
             params:(NSDictionary *)params
            progress:(UIProgressView *)progressView
            success:(HttpSuccessBlock)success
            failure:(HttpFailureBlock)failure {
    AFHttpClient *manager = [AFHttpClient sharedClient];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",nil];
    [manager GET:path parameters:params progress:^(NSProgress * _Nonnull uploadProgress) {
        [progressView setProgress:uploadProgress.fractionCompleted];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success == nil) return;
        success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure == nil) return;
        failure(error);
    }];
    
}




#pragma mark POST上传图片
+ (void)postImagePath:(NSString *)path
               params:(NSDictionary *)params
                image:(NSString *)imagePath
             progress:(UIProgressView *)progressView
              success:(HttpSuccessBlock)success
              failure:(HttpFailureBlock)failure {
    AFHttpClient *manager = [AFHttpClient sharedClient];
    
    //设置基础URL
    path = [NSString stringWithFormat:@"http://api2.pianke.me/user/reg"];
    //设置当前POST请求
    [manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //从目标路径读取图片
        UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
        //压缩当前图片
        NSData *imageData = UIImageJPEGRepresentation(image, 1);
        
        [formData appendPartWithFileData:imageData name:@"iconfile" fileName:imagePath mimeType:@"image/png"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        [progressView setProgress:uploadProgress.fractionCompleted];
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if (success == nil) return;
            success(responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            if (failure == nil) return;
            failure(error);
    }];
    
}


//第一个参数是下载地址，第二个参数是下载成功后文件保存的路径
+ (void)downloadWithURL:(NSString *)downloadURLString targetPath:(NSString *)targetPath {
    
//    NSURL *downloadURL = [NSURL URLWithString:downloadURLString];
//    NSURLRequest *downloadRequest = [[NSURLRequest alloc]initWithURL:downloadURL] ;
//    //创建下载任务
//    AFDownloadRequestOperation *downloadOperation = [[AFDownloadRequestOperation alloc]initWithRequest:downloadRequest  targetPath:targetPath shouldResume:YES];
//    
//    //设置进度
//    [downloadOperation setProgressiveDownloadProgressBlock:^(AFDownloadRequestOperation *operation, NSInteger bytesRead, long long totalBytesRead, long long totalBytesExpected, long long totalBytesReadForFile, long long totalBytesExpectedToReadForFile) {
//        
//    }];
//    //可以覆盖
//    [downloadOperation setShouldOverwrite:YES];
//    //设置完成任务
//    [downloadOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //下载成功
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        //下载失败
//    }];
//    
//    //设置background下载
//    [downloadOperation setShouldExecuteAsBackgroundTaskWithExpirationHandler:^{
//        
//    }];
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    
    NSURL *URL = [NSURL URLWithString:downloadURLString];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    // 创建下载任务
    NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        return [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]];
    } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
        NSLog(@"File downloaded to: %@", filePath);
    }];
    [downloadTask resume];
}


@end
